<template>
  <div class="register-container">
    <el-row>
      <el-col :lg="14" :md="11" :sm="24" :xl="14" :xs="24">
        <el-button
          v-if="!isCallBack"
          class="register-btn"
          type="primary"
          @click="handleInstallApp"
        >
          {{ translateTitle('企业微信应用安装') }}
        </el-button>
      </el-col>
    </el-row>
  </div>
</template>

<script>
  import { domain } from '@/config'
  import { translateTitle } from '@/utils/i18n'
  import { getPreAuthUrl, setAuthCode } from '@/api/install'
  import { useSettingsStore } from '@/store/modules/settings'
  import router from '@/router'
  import qs from 'qs'

  export default defineComponent({
    name: 'Install',
    setup() {
      const state = reactive({
        isCallBack: false,
        authCode: '',
      })

      const $baseConfirm = inject('$baseConfirm')
      const handleInstallApp = async () => {
        const param = {
          redirectUri: `http://${domain}/dksb#install`,
          //authType: 0, //授权类型：0 正式授权， 1 测试授权。不填默认是正式授权
        }
        console.log(domain)
        // const param = {
        //   redirectUri: `${window.location.protocol}//${window.location.host}:${window.location.port}${window.location.pathname}#install`,
        // }
        const { data: authurl } = await getPreAuthUrl(param).catch(() => {})
        $baseConfirm(`点击确定进入腾讯应用授权页面`, null, async () => {
          window.location.href = authurl
          //await router.push('/index')
        })
      }

      onMounted(async () => {
        let data = router.currentRoute.value.query
        if (!data.auth_code) data = qs.parse(document.location.search.slice(1))
        if (data && data.auth_code) {
          state.authCode = data.auth_code
          state.isCallBack = true
          const {
            data: { corpId },
          } = await setAuthCode(data).catch(() => {})

          const settingsStore = useSettingsStore()
          settingsStore.setCorpId(corpId)
          $baseConfirm(`点击确定进入应用首页`, null, async () => {
            //window.location.href = './index'
            await router.push('/index')
          })
        }
      })

      return {
        ...toRefs(state),
        translateTitle,
        handleInstallApp,
      }
    },
  })
</script>

<style lang="scss" scoped>
  .register-container {
    height: 100vh;
    min-height: 700px;

    .register-btn {
      display: inherit;
      width: 220px;
      height: 50px;
      margin-top: 5px;
      background: var(--el-color-primary);
      border: 0;

      &:hover {
        opacity: 0.9;
      }
    }
  }
</style>
